package com.sun.androidexerciseproject.function.task;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.birbit.android.jobqueue.Job;
import com.birbit.android.jobqueue.Params;
import com.birbit.android.jobqueue.RetryConstraint;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Description:
 * File: MyJob.java
 * Author: Administrator
 * Create: 2019/3/16 0016 下午 15:56
 */
public class MyJob extends Job {
    private static final String TAG = "MyJob";
    private String mText;
    private int mSleepTime;

    protected MyJob(String text) {
        super(new Params(1).persist().delayInMs(500));
        mText = text;
        mSleepTime = 5;
        Log.d(TAG, mText + " init");
    }

    @Override
    public void onAdded() {
        Log.d(TAG, mText + " onAdded");
    }

    @Override
    public void onRun() throws Throwable {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
        Request request = new Request.Builder().url("https://www.baidu.com").build();
        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, mText + " onRun onFailure");

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, mText + " onRun onResponse reason " + response.body().string());
            }
        });
    }

    @Override
    protected void onCancel(int cancelReason, @Nullable Throwable throwable) {
        Log.d(TAG, mText + " onCancel reason " + throwable.getMessage());
    }

    @Override
    protected RetryConstraint shouldReRunOnThrowable(@NonNull Throwable throwable, int runCount, int maxRunCount) {
        return RetryConstraint.createExponentialBackoff(runCount, maxRunCount);
    }
}
